/*
 * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.pig4cloud.pig.gateway.filter;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.gateway.config.GatewayConfigProperties;
import com.pig4cloud.pig.gateway.config.GatewayConfiguration;
import com.bblocks.common.Constant;
import com.bblocks.enums.MDCFieldEnum;
import com.bblocks.util.TraceIdUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.addOriginalRequestUrl;

/**
 * @author lengleng
 * @date 2019/2/1
 * <p>
 * 全局拦截器，作用所有的微服务
 * <p>
 * 1. 对请求头中参数进行处理 from 参数进行清洗 2. 重写StripPrefix = 1,支持全局
 * <p>
 * 支持swagger添加X-Forwarded-Prefix header （F SR2 已经支持，不需要自己维护）
 */
@Slf4j
@RequiredArgsConstructor
public class PigRequestGlobalFilter implements GlobalFilter, Ordered {

	private final GatewayConfigProperties configProperties;

	/**
	 * Process the Web request and (optionally) delegate to the next {@code WebFilter}
	 * through the given {@link GatewayFilterChain}.
	 * @param exchange the current server exchange
	 * @param chain provides a way to delegate to the next filter
	 * @return {@code Mono<Void>} to indicate when request processing is complete
	 */
	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		//0、提取token（EncryptionTokenDecoderFilter 设置）
		String token = exchange.getAttribute(Constant.ACCESS_TOKEN_KEY);

		// 1. 清洗请求头中from 参数
		List<String> froms = exchange.getRequest().getHeaders().get(SecurityConstants.FROM);
		ServerHttpRequest request = exchange.getRequest().mutate()
				.headers(httpHeaders -> {
					httpHeaders.remove(SecurityConstants.FROM);
					httpHeaders.remove(Constant.ACCESS_TOKEN_KEY);
				} )
				.build();

		// 2. 重写StripPrefix
		addOriginalRequestUrl(exchange, request.getURI());
		String rawPath = request.getURI().getRawPath();
		String newPath = "/" + Arrays.stream(StringUtils.tokenizeToStringArray(rawPath, "/")).skip(1L)
				.collect(Collectors.joining("/"));

		//3.添加请求来源，gateway
		String ip = ((Map<String,String>)exchange.getAttributes().get(GatewayConfiguration.CONTEXT_MAP)).get(MDCFieldEnum.IP.name());
		ServerHttpRequest newRequest = null;
		if(CollUtil.isNotEmpty(froms) && SecurityConstants.FROM_INNER.equals(froms.get(0) )
				&& configProperties.getSafeIps().contains(ip)){//白名单且标位为内部调用的，标记为：from:inner
			newRequest = request.mutate().path(newPath)
					.header(SecurityConstants.FROM,SecurityConstants.FROM_GW_INNER)//3.添加请求来源，gateway_inner
					.header(TraceIdUtils.TRACE_ID,TraceIdUtils.getTraceId(false))
					.header(Constant.ACCESS_TOKEN_KEY,token)
					.header(Constant.REQUEST_START_TIME,String.valueOf(System.currentTimeMillis()))
					.build();
		}else{
			newRequest = request.mutate().path(newPath)
					.header(SecurityConstants.FROM,SecurityConstants.FROM_GW)//3.添加请求来源，gateway
					.header(TraceIdUtils.TRACE_ID,TraceIdUtils.getTraceId(false))
					.header(Constant.ACCESS_TOKEN_KEY,token)
					.header(Constant.REQUEST_START_TIME,String.valueOf(System.currentTimeMillis()))
					.build();
		}

		exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());


		//先暂时放此处清理MDC信息
		MDC.clear();
		return chain.filter(exchange.mutate().request(newRequest.mutate().build()).build());
	}


	@Override
	public int getOrder() {
		return 2;
	}

}
